package com.fingard.dsp.web.page;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDbHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directConfig.FileSaveSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.interact.DownloadFileReq;
import com.fingard.dsp.interact.DownloadFileResp;
import com.fingard.dsp.interact.FileServerInvokerBase;
import com.fingard.dsp.interact.IFileServerInvoker;
import com.fingard.dsp.interact.custom.nci.wsdl.AutoImageCenter;
import com.fingard.dsp.interact.custom.nci.wsdl.AutoImageCenterServiceLocator;
import com.fingard.dsp.web.HttpRequest;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;

public class ReceiptDetail extends PageBase {

	//public StringBuilder sbLog;
	public ReceiptDetail(){
		//sbLog = p_sb;
	}
	
	/**根据查询字符串取得回单map
	 * @throws UnsupportedEncodingException */
	public static ReceiptMapping getMapByQryStr(HttpRequest pRequest) throws UnsupportedEncodingException{
		HashMap<String,String> qryMap = pRequest.getQryKeyValues();
		if(!qryMap.containsKey("act") && !qryMap.containsKey("receiptno") && !qryMap.containsKey("busref")){
			qryMap = pRequest.getFormKeyValues();
		}
		String reqbatchno="";
		String asknumber="";
		String act = "";
		String receiptno="";
		String busref = "";
		String busdate = "";
		
		Iterator<String> iter = qryMap.keySet().iterator();
        while (iter.hasNext()) {
            String eachKey = iter.next();
            if("receiptno".equals(eachKey)){
            	if(StringHelper.hasAnyChar(qryMap.get(eachKey))){
            		receiptno = qryMap.get(eachKey);
            	}
    		}else if("busref".equals(eachKey)){
    			if(StringHelper.hasAnyChar(qryMap.get(eachKey))){
            		busref = qryMap.get(eachKey);
            	}
    		}else if("reqbatchno".equals(eachKey)){
    			reqbatchno = qryMap.get(eachKey);
    		}else if("asknumber".equals(eachKey)){
    			asknumber = qryMap.get(eachKey);
    		}else if("act".equals(eachKey)){
    			act = qryMap.get(eachKey);
    		}else if("busdate".equals(eachKey)){
    			busdate = qryMap.get(eachKey);
    		}
        }
		
		ReceiptMapping receiptMp = new ReceiptMapping();
		receiptMp.reqBatchNo = reqbatchno.trim();
		receiptMp.askNumber = asknumber.trim();
		receiptMp.receiptNo = receiptno.trim();
		receiptMp.busRef = busref.trim();
		receiptMp.ownAct = act.trim();
		if(StringHelper.hasAnyChar(busdate)){
			try{
				receiptMp.busDate = Integer.parseInt(busdate);
			}catch(Exception e){
				receiptMp.busDate = Integer.parseInt(Format.Date8Format.format(new Date()));
				FGBiz.limitMsg.exception("web."+pRequest.getPage(), e);
			}
		}
		//moneyway=收支方向（1支出，2收入）&isrefund=是否冲正产生（1是，0否）&
		//amount=金额（绝对值）
		if(qryMap.containsKey("moneyway")){
			receiptMp.moneyWay = qryMap.get("moneyway");
		}
		if(qryMap.containsKey("amount")){
			String amt = qryMap.get("amount").trim();
			if(StringHelper.hasAnyChar(amt) && StringHelper.isAmount(amt)){
				amt = StringHelper.trimStart(amt, "-");//取绝对值
				receiptMp.amount = new BigDecimal(amt);
			}
		}
		return receiptMp;
	}
	
	@Override
	public void pageLoad() throws Exception{
		
		/*
		地址?bank=银行直联代码&receiptno=回单编号&busref=业务参考号&reqbatchno=支付批号&asknumber=支付流水号&directpayway=直联支付方式&abstract=对账码&moneyway=收支方向（1支出，2收入）&isrefund=是否冲正产生（1是，0否）&amount=金额（绝对值）

		对于历史明细，传bank=银行直联代码&receiptno=回单编号&busref=业务参考号&abstract=对账码&moneyway=收支方向（1支出，2收入）&amount=金额（绝对值），
		如
		http://127.0.0.1/receiptdetail?bank=308&receiptno=111222333&busref=83838333&abstract=312020202&moneyway=1&amount=500.45

		对于交易单，传bank=银行直联代码&reqbatchno=支付批号&asknumber=支付流水号&directpayway=直联支付方式&abstract=对账码&isrefund=是否冲正产生（1是，0否）&amount=金额（绝对值）
		如
		http://127.0.0.1/receiptdetail?bank=308&reqbatchno=211222222&asknumber=238388333&directpayway=2&abstract=31488048772&isrefund=0&amount=600.43
		        		 * */
		ReceiptMapping rcptQryMp = getMapByQryStr(httpContext.request);
		
		ArrayList<String> refList = new ArrayList<String>();
		if(StringHelper.hasAnyChar(rcptQryMp.receiptNo)){
    		refList.add(rcptQryMp.receiptNo);
    	}
		if(StringHelper.hasAnyChar(rcptQryMp.busRef)){
    		refList.add(rcptQryMp.busRef);
    	}
		
        
		if(StringHelper.hasAnyChar(rcptQryMp.reqBatchNo) || StringHelper.hasAnyChar(rcptQryMp.askNumber)){
			refList.add(StringHelper.join("_", rcptQryMp.reqBatchNo, rcptQryMp.askNumber));
			if(StringHelper.hasAnyChar(rcptQryMp.askNumber)){
				refList.add(rcptQryMp.askNumber);
			}
			if(StringHelper.hasAnyChar(rcptQryMp.reqBatchNo)){
				refList.add(rcptQryMp.reqBatchNo);
			}
		}
		
		if(StringHelper.isNullOrEmpty(rcptQryMp.askNumber)){
			String page = httpContext.request.getPage().toLowerCase();
			String[] fname = StringHelper.splitFileNameAndExt(page);
			String[] batchAndAsk = fname[0].split("_");
			
			if(batchAndAsk.length>1){
				rcptQryMp.askNumber = batchAndAsk[batchAndAsk.length-1];//取最后一段
			}else{
				rcptQryMp.askNumber = batchAndAsk[0];
			}
			refList.add(rcptQryMp.askNumber);
		}
		
		String contentDisposition = "attachment";
		
		Date today = new Date();
		ArrayList<Date> dateList = new ArrayList<Date>();
		if(rcptQryMp.busDate > 0){
			Date bDate = rcptQryMp.getBusDate();
			dateList.add(bDate);//参数月
			dateList.add(DateHelper.addMonths(bDate, -1));//前一月
			if(DateHelper.compareMonth(today, bDate)>0){
				dateList.add(DateHelper.addMonths(bDate, 1));//后一月
			}
		}else{
			dateList.add(today);//当前月
			dateList.add(DateHelper.addMonths(today, -1));//前一个月
			dateList.add(DateHelper.addMonths(today, -2));//前两个月
		}
		FileSaveSet fileSet = FGBiz.dspCenter.dspConfig.getFileSaveSet("receipt");
		boolean isRetHtml = false;//已经组装好了html
		int loopCount = 0;//循环月次数
		for(Date eachDate : dateList){
			ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
			try{
				loopCount++;
				receiptHelper = new ReceiptDataHelper("", eachDate);
				if(receiptHelper.existTable()){
					ReceiptData rData = null;
					if(StringHelper.hasAnyChar(rcptQryMp.receiptNo)){
						rData = receiptHelper.loadFromDbByReceiptNo(rcptQryMp.ownAct, rcptQryMp.receiptNo);
					}
					if(rData == null && StringHelper.hasAnyChar(rcptQryMp.busRef)){
						rData = receiptHelper.loadFromDbByBusRef(rcptQryMp.ownAct, rcptQryMp.busRef);
					}
					if(rData == null && StringHelper.hasAnyChar(rcptQryMp.askNumber)){
						rData = receiptHelper.loadFromDbByBusRef(rcptQryMp.ownAct, rcptQryMp.askNumber);
					}
					//根据关联号查不到时，按日期+金额查找
					if(rData == null && loopCount==1 && rcptQryMp.amount != null && rcptQryMp.busDate>0){
						rData = receiptHelper.loadFromDbByAmount(rcptQryMp.busDate, rcptQryMp.ownAct, rcptQryMp.amount, rcptQryMp.moneyWay);
					}
					if(rData != null){
						
						if(StringHelper.isNullOrEmpty(rData.localFile) && !"2".equals(rData.downState)){
							httpContext.response.respMsg = setRetHtml("回单文件暂未下载完成");
							httpContext.response.setContentType("htm", "");
							return;
						}
						
						String ext = StringHelper.getFileExt(rData.localFile);
						String fileName = rData.ownAct+"_"+rData.busDate+"_"+rData.receiptNo+"."+ext;
						contentDisposition = "attachment;filename="+fileName;
						FGBiz.logTrace.debug("web.ReceiptDetail", "相对文件路径：" + rData.localFile);
						ReceiptProConfig proConfig = ReceiptPro.getReceiptProConfig();
						String filePath = proConfig.localSaveMainDir+File.separator+StringHelper.trimStartFileSp(rData.localFile);
						filePath = StringHelper.replaceFileSp(filePath);
						if(StringHelper.hasAnyChar(rData.localFile) && FileHelper.existFile(filePath)){
							httpContext.response.isRtnBytes = true;
							httpContext.response.respBytes = FileHelper.readFileBytes(filePath);
							
							if("1".equals(httpContext.request.getQryStrValue("down"))){
								httpContext.response.setContentType("down",httpContext.request.webBrowser);
								httpContext.response.contentDisposition = contentDisposition;
							}else{
								httpContext.response.setContentType(StringHelper.getFileExt(filePath), httpContext.request.webBrowser);
							}
							return;
						}else{
							
							FGBiz.logTrace.error("web.ReceiptDetail", "文件不存在：" + filePath);
							
							FGBiz.limitMsg.add(this.getClass().getName(), "数据已存在，查找本地文件"+rData.localFile+"不存在");
							boolean isDown = false;
							if("1".equals(httpContext.request.getQryStrValue("down"))){
								isDown = true;
							}
							if("nci".equals(FGBiz.dspCenter.dspSet.customCode.toLowerCase())){
								if(isDown){
									httpContext.response.respMsg = "当前回单文件"+StringHelper.getFileName(rData.localFile)+"已不支持下载";
								}else{
									
									try{
										String url = fileSet.getParam("url", "");
										FGBiz.logTrace.info("nci", "webservice地址："+url);
										String clientcode = fileSet.getParam("clientcode", "");
										String servicecode = fileSet.getParam("servicecode", "");
										String safetyKey = fileSet.getParam("safetyKey", "");//约定safetyKey ZJImageCenter
										String servername = fileSet.getParam("servername", "");
										String timemd5Key = fileSet.getParam("timemd5Key", "");
										String useraccount = fileSet.getParam("useraccount", "");//admin
										AutoImageCenterServiceLocator imgService = new AutoImageCenterServiceLocator();
										imgService.setAutoImageCenterWsEndpointAddress(url);
										AutoImageCenter imgCenter = imgService.getAutoImageCenterWs();
										StringBuilder sbImg = new StringBuilder();
										String reqTime = Format.DateTime14Format.format(new Date());
										String digestReq = reqTime+servicecode+clientcode+safetyKey;
										byte[] dgReqBytes = digestReq.getBytes("utf-8");
										String dgResult = DigestHelper.cryptoMD5RetHexStr(dgReqBytes);
										
										String timeToDg = reqTime+timemd5Key;//ImageCenterFK
										byte[] timeToBytes = timeToDg.getBytes("utf-8");
										String timeMd5 = DigestHelper.cryptoMD5RetHexStr(timeToBytes);
										
										FGBiz.logTrace.info("nci", "ticket:md5("+digestReq+")="+dgResult);
										FGBiz.logTrace.info("nci", "timemd5:md5("+timeToDg+")="+timeMd5);
										
										sbImg.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
										"<params>\r\n"+
										"<safety>\r\n"+
										"  <clientcode>"+clientcode+"</clientcode>\r\n"+
										"  <servicecode>"+servicecode+"</servicecode>\r\n"+
										"  <time>"+reqTime+"</time>\r\n"+
										"  <ticket>"+dgResult+"</ticket>\r\n"+
										"</safety>\r\n"+
										"<serverbody>\r\n"+
										"  <servername>"+servername+"</servername>\r\n"+
										"  <services>\r\n"+
										"    <service>\r\n"+
										"      <barcode>"+rData.receiptNo+"_"+rData.ownAct+"</barcode>\r\n"+
										"      <type>9</type>"+
										"      <time>"+reqTime+"</time>"+
										"      <timemd5>"+timeMd5+"</timemd5>"+//时间+”ImageCenterFK” 的MD5值，用于校验链接是否有效
										"      <useraccount>"+useraccount+"</useraccount>"+
										"      <isapp></isapp>"+
										"    </service>\r\n"+
										"  </services>\r\n"+
										"</serverbody>\r\n"+
										"</params>");
										FGBiz.logTrace.info("nci", "获取地址请求报文："+sbImg.toString());
										String retImgAddr = imgCenter.imageInterfaceService(sbImg.toString());
										FGBiz.logTrace.info("nci", "响应的报文："+retImgAddr);
										XmlTextReader xmlReader = new XmlTextReader(retImgAddr);
										String result = xmlReader.getFirstText("/root/items/item/result");
										String errormsg = xmlReader.getFirstText("/root/items/item/errormsg");
										String success = xmlReader.getFirstText("/root/items/item/success");
										if("0".equals(result)){
											httpContext.response.setContentType("html", httpContext.request.webBrowser);
											StringBuilder sbHtml = new StringBuilder();
											sbHtml.append("<html>\r\n");
											sbHtml.append("<head>\r\n");
											sbHtml.append("  <title>回单查看</title>\r\n");
											sbHtml.append("</head>\r\n");
											sbHtml.append("<body>\r\n");
											sbHtml.append("<script language=\"javascript\" type=\"text/javascript\">\r\n");
											sbHtml.append("window.location.href=\""+success+"\";\r\n");
											sbHtml.append("</script>\r\n");
											sbHtml.append("地址："+success+"\r\n");
											sbHtml.append("</body>\r\n");
											sbHtml.append("</html>");
											httpContext.response.respMsg = sbHtml.toString();
											isRetHtml = true;
										}else if(StringHelper.hasAnyChar(errormsg)){
											httpContext.response.respMsg = errormsg;
										}else{
											httpContext.response.respMsg = retImgAddr;
										}
										
									}catch(Exception ex){
										httpContext.response.respMsg = "调用影像接口出现异常："+LogHelper.getStackTrace(ex);
										FGBiz.logTrace.exception("nci", ex);
									}
								}
							}
							
						}
						httpContext.response.respMsg = setRetHtml("回单数据已存在，但文件未下载");
						httpContext.response.setContentType("htm", "");
						return;
					}else{
						FGBiz.logTrace.debug("web.ReceiptDetail", "查找分区库分区表为空"+Format.Date10Format.format(eachDate));
					}
				}
			}catch(Exception ex){
				if(receiptHelper!=null){
					receiptHelper.close();
				}
				FGBiz.logTrace.exception("web.ReceiptDetail", ex);
				httpContext.response.respMsg = setRetHtml(LogHelper.getStackTrace(ex));
				httpContext.response.setContentType("htm", "");
				return;
			}
		}
		
		
		ReceiptMapping rcptMp = ReceiptDbHelper.getRcptMpByAny(rcptQryMp);
		
		boolean isExistData = false;
		if(rcptMp!=null){
			isExistData = true;
			String mpReceiptFile = rcptMp.receiptFile;
			if(mpReceiptFile == null){
				mpReceiptFile = "";
			}
			String rcptFilePath1 = fileSet.getMainDir(rcptMp.bank) + File.separator + StringHelper.replaceFileSp(StringHelper.trimStartFileSp(mpReceiptFile));
			String rcptFilePath2 = fileSet.getMainDir(rcptMp.bank) + File.separator + StringHelper.replaceFileSp(StringHelper.trimStartFileSp(mpReceiptFile.toLowerCase()));
			String ext = StringHelper.getFileExt(rcptFilePath1);
			contentDisposition = "attachment;filename="+StringHelper.getFileName(rcptFilePath1);
			String cmpSaveType = "";
			if(StringHelper.hasAnyChar(fileSet.saveType)){
				cmpSaveType = fileSet.saveType.toLowerCase();
			}
			if(mpReceiptFile.length() > 0 && FileHelper.existFile(rcptFilePath1)){
				httpContext.response.isRtnBytes = true;
				httpContext.response.respBytes = FileHelper.readFileBytes(rcptFilePath1);
				
				if("1".equals(httpContext.request.getQryStrValue("down"))){
					httpContext.response.setContentType("down",httpContext.request.webBrowser);
					httpContext.response.contentDisposition = contentDisposition;
				}else{
					httpContext.response.setContentType(ext,httpContext.request.webBrowser);
				}
				return;
			}else if(mpReceiptFile.length() > 0 && FileHelper.existFile(rcptFilePath2)){
				httpContext.response.isRtnBytes = true;
				httpContext.response.respBytes = FileHelper.readFileBytes(rcptFilePath2);
				if("1".equals(httpContext.request.getQryStrValue("down"))){
					httpContext.response.setContentType("down",httpContext.request.webBrowser);
					httpContext.response.contentDisposition = contentDisposition;
				}else{
					httpContext.response.setContentType(ext,httpContext.request.webBrowser);
				}
				return;
			}else if("custom.fileserver".equals(cmpSaveType) || "oss".equals(cmpSaveType)){
				
				String fileId = rcptMp.customFileId;
				try {
                    String className = "";
                    if("custom.fileserver".equals(cmpSaveType)){
                    	className = "com.fingard.dsp.interact.custom." + FGBiz.dspCenter.dspSet.customCode.toLowerCase() + "." + "FileServerInvoker";
                    }else{
                    	className = "com.fingard.dsp.interact.oss." + fileSet.ossSet.ossType.toLowerCase() + "." + "FileServerInvoker";
                    }
                    Class<?> fsClass = Class.forName(className);
                    if (fsClass != null) {
                    	FileServerInvokerBase fsClassBase = (FileServerInvokerBase) fsClass.newInstance();
                    	fsClassBase.fsSet = fileSet;
                    	IFileServerInvoker iFsInvoker = (IFileServerInvoker) fsClassBase;
                    	DownloadFileReq downReq = new DownloadFileReq();
                    	downReq.fileId = fileId;
                    	DownloadFileResp downResp = iFsInvoker.downloadFile(downReq);
                    	if(downResp.isCompleted){
                    		httpContext.response.respBytes = downResp.fileBytes;
                    		httpContext.response.isRtnBytes = true;
                    		if("1".equals(httpContext.request.getQryStrValue("down"))){
            					httpContext.response.setContentType("down", httpContext.request.webBrowser);
            					httpContext.response.contentDisposition = contentDisposition;
            				}else{
            					httpContext.response.setContentType(ext,httpContext.request.webBrowser);
            				}
                    		return;
                    	}else{
                    		httpContext.response.respMsg = downResp.sbMsg.toString();
                    	}
                    }else{
                    	httpContext.response.respMsg = "不存在类"+className;
                    }
                }catch (Throwable t) {
                	//resp.connState = ConnState.CLASS_NOT_FOUND;
                	httpContext.response.respMsg = LogHelper.getStackTrace(t);
                	FGBiz.limitMsg.exception("ReceiptDetail", t);
                }
			}else{
				httpContext.response.respMsg = "数据已存在，但文件"+rcptFilePath1+"（或"+rcptFilePath2+"）不存在";
				FGBiz.limitMsg.add(this.getClass().getName(), "数据已存在，查找文件"+rcptFilePath1+"（或"+rcptFilePath2+"）不存在");
				boolean isDown = false;
				if("1".equals(httpContext.request.getQryStrValue("down"))){
					isDown = true;
				}
				if("nci".equals(FGBiz.dspCenter.dspSet.customCode.toLowerCase())){
					if(isDown){
						httpContext.response.respMsg = "当前回单文件"+StringHelper.getFileName(rcptFilePath1)+"已不支持下载";
					}else{
						
						try{
							String url = fileSet.getParam("url", "");
							FGBiz.logTrace.info("nci", "webservice地址："+url);
							String clientcode = fileSet.getParam("clientcode", "");
							String servicecode = fileSet.getParam("servicecode", "");
							String safetyKey = fileSet.getParam("safetyKey", "");//约定safetyKey ZJImageCenter
							String servername = fileSet.getParam("servername", "");
							String timemd5Key = fileSet.getParam("timemd5Key", "");
							String useraccount = fileSet.getParam("useraccount", "");//admin
							AutoImageCenterServiceLocator imgService = new AutoImageCenterServiceLocator();
							imgService.setAutoImageCenterWsEndpointAddress(url);
							AutoImageCenter imgCenter = imgService.getAutoImageCenterWs();
							StringBuilder sbImg = new StringBuilder();
							String reqTime = Format.DateTime14Format.format(new Date());
							String digestReq = reqTime+servicecode+clientcode+safetyKey;
							byte[] dgReqBytes = digestReq.getBytes("utf-8");
							String dgResult = DigestHelper.cryptoMD5RetHexStr(dgReqBytes);
							
							String timeToDg = reqTime+timemd5Key;//ImageCenterFK
							byte[] timeToBytes = timeToDg.getBytes("utf-8");
							String timeMd5 = DigestHelper.cryptoMD5RetHexStr(timeToBytes);
							
							FGBiz.logTrace.info("nci", "ticket:md5("+digestReq+")="+dgResult);
							FGBiz.logTrace.info("nci", "timemd5:md5("+timeToDg+")="+timeMd5);
							
							sbImg.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
							"<params>\r\n"+
							"<safety>\r\n"+
							"  <clientcode>"+clientcode+"</clientcode>\r\n"+
							"  <servicecode>"+servicecode+"</servicecode>\r\n"+
							"  <time>"+reqTime+"</time>\r\n"+
							"  <ticket>"+dgResult+"</ticket>\r\n"+
							"</safety>\r\n"+
							"<serverbody>\r\n"+
							"  <servername>"+servername+"</servername>\r\n"+
							"  <services>\r\n"+
							"    <service>\r\n"+
							"      <barcode>"+rcptMp.receiptNo+"_"+rcptMp.ownAct+"</barcode>\r\n"+
							"      <type>9</type>"+
							"      <time>"+reqTime+"</time>"+
							"      <timemd5>"+timeMd5+"</timemd5>"+//时间+”ImageCenterFK” 的MD5值，用于校验链接是否有效
							"      <useraccount>"+useraccount+"</useraccount>"+
							"      <isapp></isapp>"+
							"    </service>\r\n"+
							"  </services>\r\n"+
							"</serverbody>\r\n"+
							"</params>");
							FGBiz.logTrace.info("nci", "获取地址请求报文："+sbImg.toString());
							String retImgAddr = imgCenter.imageInterfaceService(sbImg.toString());
							FGBiz.logTrace.info("nci", "响应的报文："+retImgAddr);
							XmlTextReader xmlReader = new XmlTextReader(retImgAddr);
							String result = xmlReader.getFirstText("/root/items/item/result");
							String errormsg = xmlReader.getFirstText("/root/items/item/errormsg");
							String success = xmlReader.getFirstText("/root/items/item/success");
							if("0".equals(result)){
								httpContext.response.setContentType("html", httpContext.request.webBrowser);
								StringBuilder sbHtml = new StringBuilder();
								sbHtml.append("<html>\r\n");
								sbHtml.append("<head>\r\n");
								sbHtml.append("  <title>回单查看</title>\r\n");
								sbHtml.append("</head>\r\n");
								sbHtml.append("<body>\r\n");
								sbHtml.append("<script language=\"javascript\" type=\"text/javascript\">\r\n");
								sbHtml.append("window.location.href=\""+success+"\";\r\n");
								sbHtml.append("</script>\r\n");
								sbHtml.append("地址："+success+"\r\n");
								sbHtml.append("</body>\r\n");
								sbHtml.append("</html>");
								httpContext.response.respMsg = sbHtml.toString();
								isRetHtml = true;
							}else if(StringHelper.hasAnyChar(errormsg)){
								httpContext.response.respMsg = errormsg;
							}else{
								httpContext.response.respMsg = retImgAddr;
							}
							
						}catch(Exception ex){
							httpContext.response.respMsg = "调用影像接口出现异常："+LogHelper.getStackTrace(ex);
							FGBiz.logTrace.exception("nci", ex);
						}
					}
				}
			}
		}
	
		
		
		if(!httpContext.response.isRtnBytes){
			for(int i=0;i<refList.size();i++){
				if(StringHelper.hasAnyChar(refList.get(i))){
					String reqRef = refList.get(i);
					String targetDir = StringHelper.getDirPathUsingSplitGiveUpLastOne(reqRef, 3);
					String dataMapFile = fileSet.getMainDir("") + File.separator + targetDir+File.separator+"mapping_"+rcptQryMp.ownAct+".txt";
					//System.out.println("mapfile:"+dataMapFile);
					File mFile = new File(dataMapFile);
					if(mFile.exists()){
						XElement trgXE = null;
						XmlTextReader xmlRd = new XmlTextReader("<r>" + FileHelper.readToString(mFile, "gbk") + "</r>");
						while(xmlRd.read("/r/item")){
							XElement xe = xmlRd.readedXElement;
							String ref = xe.getAttrValue("ref");
							if(ref==null){
								ref = "";
							}
							//System.out.println("reqRef:"+reqRef+",ref:"+ref);
							if(reqRef.toLowerCase().equals(ref.toLowerCase())){
								trgXE = xe;
								//break;
							}
						}
						if(trgXE!=null){
							String fileName = trgXE.getAttrValue("fileName");
							String ext = StringHelper.getFileExt(fileName);
							contentDisposition = "attachment;filename="+StringHelper.getFileName(fileName);
							if("custom.fileServer".equals(fileSet.saveType)){
								
								String fileId = trgXE.getAttrValue("customFileId");
								//System.out.println("customFileId:"+fileId);
								try {
				                    String className = "com.fingard.dsp.interact.custom." + FGBiz.dspCenter.dspSet.customCode.toLowerCase() + "." + "FileServerInvoker";
				                    Class<?> fsClass = Class.forName(className);
				                    if (fsClass != null) {
				                    	FileServerInvokerBase fsClassBase = (FileServerInvokerBase) fsClass.newInstance();
				                    	fsClassBase.fsSet = fileSet;
				                    	
				                    	//sbLog.append("downloadUrl:" + fileSet.downloadUrl+"\r\n");
				                    	//sbLog.append("username:" + fileSet.username+"\r\n");
				                    	//sbLog.append("systemName:" + fileSet.systemName+"\r\n");
				                    	IFileServerInvoker iFsInvoker = (IFileServerInvoker) fsClassBase;
				                    	DownloadFileReq downReq = new DownloadFileReq();
				                    	downReq.fileId = fileId;
				                    	DownloadFileResp downResp = iFsInvoker.downloadFile(downReq);
				                    	if(downResp.isCompleted){
				                    		httpContext.response.respBytes = downResp.fileBytes;
				                    		httpContext.response.isRtnBytes = true;
				                    		if("1".equals(httpContext.request.getQryStrValue("down"))){
				            					httpContext.response.setContentType("down",httpContext.request.webBrowser);
				            					httpContext.response.contentDisposition = contentDisposition;
				            				}else{
				            					httpContext.response.setContentType(ext,httpContext.request.webBrowser);
				            				}
				                    		return;
				                    	}else{
				                    		httpContext.response.respMsg = downResp.sbMsg.toString();
				                    	}
				                    }else{
				                    	httpContext.response.respMsg = "不存在类"+className;
				                    }
				                }catch (Throwable t) {
				                	//resp.connState = ConnState.CLASS_NOT_FOUND;
				                	httpContext.response.respMsg = LogHelper.getStackTrace(t);
				                }
							}else{//保存到本地目录或共享目录
								String fileDir;
								if("shareDir".equals(fileSet.saveType)){//-共享目录
									fileDir = fileSet.shareDir + File.separator + targetDir;
								}else{
									fileDir = fileSet.getMainDir("") + File.separator + targetDir;
								}
								String filePath = fileDir + File.separator + fileName;
								File resultFile = new File(filePath);
								if(resultFile.exists()){
									httpContext.response.isRtnBytes = true;
									httpContext.response.respBytes = FileHelper.readFileBytes(filePath);
									if("1".equals(httpContext.request.getQryStrValue("down"))){
										httpContext.response.setContentType("down",httpContext.request.webBrowser);
										httpContext.response.contentDisposition = contentDisposition;
									}else{
										httpContext.response.setContentType(ext,httpContext.request.webBrowser);
									}
									return;
								}else{
									//sbLog.append("目标文件"+filePath+"不存在");
									httpContext.response.isRtnBytes = false;
									httpContext.response.respMsg = "目标文件"+fileName+"不存在";
								}
							}
						}
					}
				}
			}
		}else{
			if("1".equals(httpContext.request.getQryStrValue("down"))){
				httpContext.response.setContentType("down",httpContext.request.webBrowser);
				httpContext.response.contentDisposition = contentDisposition;
			}
		}
		
		if(isRetHtml == false){
			StringBuilder sbResp = new StringBuilder();
			sbResp.append("<html><head><title>回单查看</title></head><body>\r\n<pre>");
			if(StringHelper.hasAnyChar(httpContext.response.respMsg)){
				sbResp.append(httpContext.response.respMsg+"\r\n");
			}
			if(isExistData == false){
				sbResp.append("未找到对应的电子回单文件，请执行获取回单任务后再查看\r\n");	
			}
			//Date nowDate = new Date();
			//Date cmpDate = Format.Date10Format.parse("2019-10-31");
			//if(DateHelper.compareDay(nowDate, cmpDate)<=0){
			FGBiz.logTrace.error("web"+File.separator+"ReceiptDetail", "\r\n\r\nhttp原始请求内容：\r\n"+httpContext.request.httpReceiver.getRawReqStr());
			//}
			sbResp.append("</pre>\r\n</body></html>");
			httpContext.response.respMsg = sbResp.toString();
		}
	}
	
	private String setRetHtml(String pMsg){
		StringBuilder sbResp = new StringBuilder();
		sbResp.append("<html><head><title>回单查看</title></head><body>\r\n<pre>");
		sbResp.append(pMsg);
		sbResp.append("</pre>\r\n</body></html>");
		return sbResp.toString();
	}
}
